#!/usr/bin/env python
# -*- coding:utf8 -*-
# uncompyle6 version 2.15.1
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.10 (default, Jul  1 2017, 13:36:56) 
# [GCC 4.4.6 20110731 (Red Hat 4.4.6-4)]
# Embedded file name: ./esb/esb/management/commands/sync_api_docs.py
# Compiled at: 2017-11-16 15:44:28
"""
update api_doc to db
"""
import logging
from optparse import make_option
from django.core.management.base import BaseCommand
from esb.bkcore.models import ComponentAPIDoc, ESBChannel
from esb.utils import channel_tools
from esb.management.utils.api_docs import ApiDocManager, DocNotChangedException
logger = logging.getLogger(__name__)

class Command(BaseCommand):
    option_list = BaseCommand.option_list + (
     make_option('--all', action='store_true', dest='all', help='update all api docs'),)

    def handle(self, *args, **options):
        options['all'] = True
        channels = channel_tools.get_bk_channels()
        update_api_docs(channels, is_update_all_api_doc=options['all'])


def update_api_docs(channel_config, is_update_all_api_doc):
    api_doc_manager = ApiDocManager()
    api_doc_manager.is_update_all_api_doc = is_update_all_api_doc
    for system_name, channels in channel_config.items():
        for channel in channels:
            try:
                api_data = api_doc_manager.get_api_doc(channel['comp_codename'])
            except DocNotChangedException:
                continue

            if not api_data:
                logger.warning('Oooops, No api document define found in component %(comp_name)s, you better write one.' % {'comp_name': channel['comp_codename']})
                continue
            component = ESBChannel.objects.get(path=channel['path'])
            ComponentAPIDoc.objects.update_or_create(component_id=component.id, defaults={'board': '',
               'doc_md': api_data['doc_md'],
               'doc_html': api_data['doc_html'],
               'doc_md_md5': api_data['raw_doc_md_md5']
               })
            logger.info('Document synced for api [%s](%s)', api_data['system_name'], api_data['api_name'])
